import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter<T> implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const http = host.switchToHttp();

    const request = http.getRequest<Request>();
    const response = http.getResponse<Response>();

    const statusCode = exception.getStatus();
    const exceptionMessage = exception.getResponse() as {
      message: string[];
    };
    const message = exceptionMessage?.message || exception.message;

    // console.log('错误消息', message, exceptionMessage);

    response.status(statusCode).json({
      status: statusCode,
      message: Array.isArray(message) ? message.join(', ') : message,
      success: false,
      path: request.url,
    });
  }
}
